// onload
$(document).ready(function() {
	device.regForm();
});

var device = {
	deviceUrl : contextPath + "/device"

	//등록 폼 생성
	,regForm : function() {
		var html = [];
		html.push('<form id="create" method="POST" onsubmit="device.reg(); return false;">');
		html.push('<table>');
		html.push('<tr><th align=left>DEVICE NAME</th><td><input type="text" id="name" name="name" value="";" ></td></tr>');
		html.push('<tr><th align=left>LONGITUDE</th><td><input type="text" id="longitude" name="longitude" value="";" ></td></tr>');
		html.push('<tr><th align=left>LATITUDE</th><td><input type="text" id="latitude" name="latitude";" ></td></tr>');
		html.push('</table>');
		html.push('<input type="submit" value="등록" >');
		html.push('<input type="button" value="취소" onclick="top.window.close()" >');
		$('#addDevice').html(html.join(""));
	}
	// 데이터 등록
	,reg : function() {
		if ( $.trim($("#name").val()) == "" ) {
			alert("DEVICE NAME을 입력하세요.");
			$("#name").focus();
			return;
		}
		else if ( $.trim($("#longitude").val()) == "" ) {
			alert("LONGITUDE를 입력하세요.");
			$("#longitude").focus();
			return;
		}
		else if ( $.trim($("#latitude").val()) == "" ) {
			alert("LATITUDE를 입력하세요.");
			$("#latitude").focus();
			return;
		}
		
		// form 데이터 json 으로 변환
		var json = $.toJSON($('#create').serializeJSON());
		var request = $.ajax({
			url : this.deviceUrl
			,type : 'POST'
			,contentType : 'application/json; charset=UTF-8'
			,data : json
			,dataType : 'json'
		});
		request.done(function(data) {
			//팝업창 닫고 부모창 refresh
			opener.location.reload();
			top.window.close();
		});
		request.fail(function(jqXHR, textStatus) {
			alert('Request failed: ' + textStatus);
		});
	}
};
